<?php

class Video_Controller_Browse_Add extends Nuo_Controller
{
	function execute($request)
	{

		$table = Nuo::getTable('video');

		$parentId = $request -> getParam('main-resource');

		$poster = Nuo::getUser();

		$userId = Nuo::getUserId();

		if ($parentId)
		{
			$parentItem = Nuo::getItem($parentId);
		}

		if (!$parentItem)
		{
			$parentItem = Nuo::getUser();
		}

		//Video_Form_Add
		$form = Nuo::getObject('video/add', 'form');

		if ($request -> isPost() && $form -> isValid($_POST))
		{
			$data = $form -> getData();

			$link = $data['source_url'];

			/**
			 * parse data from url.
			 */
			$videoApi = Nuo::getApi('video');

			$info = $videoApi -> getVideoInfo($link);

			if ($info)
			{
				$item = $table -> fetchNew();

				$item -> fromArray($info);

				$thumbUrl = $info['thumbnail_large'];

				$photo = Nuo::getApi('core/storage')->processImage(array('url' => str_replace('https://', 'http://', $thumbUrl)), 'video');

				if ($photo)
				{
					$item -> setPhotoFile($photo);
				}

				$item -> created_at = time();

				$item -> user_id = $userId;

				$item -> setPoster($poster) -> setResource($parentItem);

				$item -> save();

				$feed = Nuo::getApi('activity') -> addFeed(NULL, $poster, $item, 'video:addNew', $data['privacy']);

				if ($feed)
				{
					$attatchment = Nuo::getApi('core/attachment') -> addAttachment($feed, $item);
				}

				$uri = $parentItem -> getUrl('?tab=video');

				Nuo::redirect($uri);

			}
			else
			{
				$form -> setErrors('Could not support this service');
			}

		}

		return  Nuo::getView()->render('core/view/controller/browse/edit', array('form' => $form));
	}

}
